#include "page_control.h"
#include "ui_page_control.h"
#include "datamonitor.h"
#include <QTimer>
#include <QDateTime>
#include <QDebug>
#include <QJsonObject>

Page_control::Page_control(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page_control),
    m_dataMonitor(nullptr),
    m_ledBrightnessTimer(nullptr),
    m_fanSpeedTimer(nullptr),
    m_buzzerState(false)  // ✅ 初始化为关闭状态
{
    ui->setupUi(this);

    m_ledBrightnessTimer = new QTimer(this);
    m_ledBrightnessTimer->setSingleShot(true);
    connect(m_ledBrightnessTimer, &QTimer::timeout, this, &Page_control::sendLedBrightnessCommand);

    m_fanSpeedTimer = new QTimer(this);
    m_fanSpeedTimer->setSingleShot(true);
    connect(m_fanSpeedTimer, &QTimer::timeout, this, &Page_control::sendFanSpeedCommand);

    initializeDeviceStates();
    setupConnections();
}


Page_control::~Page_control()
{
    delete ui;
}

void Page_control::updateBuzzerStatusFromAlert(bool isOn)
{
    m_buzzerState = isOn;

    // ⚠️ 阻止信号循环触发
    ui->btn_quick_buzzer->blockSignals(true);
    ui->btn_quick_buzzer->setChecked(isOn);
    ui->btn_quick_buzzer->blockSignals(false);

    // 更新UI显示
    updateBuzzerUI(isOn);

    // ✅ 手动触发串口发送指令
    QString action = isOn ? "on" : "off";
    sendControlCommand("buzzer", 1, action, QJsonObject());

    qDebug() << "蜂鸣器状态已更新并发送指令:" << (isOn ? "开启" : "关闭");
}

// ✅ 新增：更新蜂鸣器UI状态
void Page_control::updateBuzzerUI(bool isOn)
{
    // 更新蜂鸣器按钮状态
    ui->btn_quick_buzzer->setChecked(isOn);
    ui->btn_quick_buzzer->setText(isOn ? "蜂鸣器\n报警" : "蜂鸣器\n静音");

    // 更新按钮样式
    if (isOn) {
        ui->btn_quick_buzzer->setStyleSheet(
            "QPushButton { color: white; background-color: #FF5722; font-weight: bold; }");
    } else {
        ui->btn_quick_buzzer->setStyleSheet(
            "QPushButton { color: black; background-color: #e0e0e0; }");
    }
}

void Page_control::setDataMonitor(DataMonitor *dataMonitor)
{
    m_dataMonitor = dataMonitor;
    qDebug() << "设备控制页面已连接到数据监控页面";
}

void Page_control::initializeDeviceStates()
{
    // 初始化LED状态 - 设置为禁用(仅显示状态)
    ui->btn_led_toggle->setText("关闭");
    ui->btn_led_toggle->setCheckable(false);
    ui->btn_led_toggle->setEnabled(false);
    ui->btn_led_toggle->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");

    ui->btn_quick_led->setText("LED灯\n关闭");
    ui->btn_quick_led->setCheckable(false);
    ui->btn_quick_led->setEnabled(false);
    ui->btn_quick_led->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");

    // 初始化风扇状态 - 设置为禁用(仅显示状态)
    ui->btn_fan_toggle->setText("关闭");
    ui->btn_fan_toggle->setCheckable(false);
    ui->btn_fan_toggle->setEnabled(false);
    ui->btn_fan_toggle->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");

    ui->btn_quick_fan->setText("风扇\n已停止");
    ui->btn_quick_fan->setCheckable(false);
    ui->btn_quick_fan->setEnabled(false);
    ui->btn_quick_fan->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");

    // 初始化其他设备状态
    ui->btn_quick_camera->setText("摄像头\n正常");
    ui->btn_quick_buzzer->setText("蜂鸣器\n静音");

    // 设置LED亮度初始值为0
    ui->slider_led_brightness->setValue(0);
    ui->label_led_value->setText("0%");

    // 设置风扇速度初始值为0
    ui->slider_fan_speed->setValue(0);
    ui->label_fan_value->setText("0%");

    // ✅ 初始化传感器数据显示为等待状态
    ui->label_temp_value->setText("--°C");
    ui->label_humidity_value->setText("--%");
    ui->label_light_value->setText("-- Lux");
    ui->label_co2_value->setText("-- ppm");
    ui->label_pressure_value->setText("-- hPa");
    ui->label_distance_value->setText("-- cm");
}

void Page_control::setupConnections()
{
    // LED亮度滑块连接 - 使用防抖机制
    connect(ui->slider_led_brightness, &QSlider::valueChanged, this, &Page_control::onLedBrightnessChanged);
    connect(ui->slider_led_brightness, &QSlider::sliderReleased, this, &Page_control::onLedSliderReleased);

    // 风扇速度滑块连接 - 使用防抖机制
    connect(ui->slider_fan_speed, &QSlider::valueChanged, this, &Page_control::onFanSpeedChanged);
    connect(ui->slider_fan_speed, &QSlider::sliderReleased, this, &Page_control::onFanSliderReleased);

    // 风扇反转开关连接
    connect(ui->btn_fan_reverse, &QPushButton::toggled, this, &Page_control::onFanReverseToggle);

    // 其他快速控制连接
    connect(ui->btn_quick_camera, &QPushButton::toggled, this, &Page_control::onQuickCameraToggle);
    connect(ui->btn_quick_buzzer, &QPushButton::toggled, this, &Page_control::onQuickBuzzerToggle);
}

void Page_control::startSensorTimer()
{
    QTimer *sensorTimer = new QTimer(this);
    connect(sensorTimer, &QTimer::timeout, this, &Page_control::updateSensorDataSimulation);
    sensorTimer->start(2000);
}

// ✅ 新增：从串口数据更新传感器显示
void Page_control::updateSensorDataFromSerial(const QVariantMap &sensorData)
{
    // 更新温度
    if (sensorData.contains("temperature")) {
        double temperature = sensorData["temperature"].toDouble();
        ui->label_temp_value->setText(QString("%1°C").arg(temperature, 0, 'f', 1));
    }

    // 更新湿度
    if (sensorData.contains("humidity")) {
        double humidity = sensorData["humidity"].toDouble();
        ui->label_humidity_value->setText(QString("%1%").arg(humidity, 0, 'f', 0));
    }

    // 更新光照强度
    if (sensorData.contains("light")) {
        double light = sensorData["light"].toDouble();
        ui->label_light_value->setText(QString("%1 Lux").arg(light, 0, 'f', 0));
    }

    // 更新CO2浓度
    if (sensorData.contains("co2")) {
        double co2 = sensorData["co2"].toDouble();
        ui->label_co2_value->setText(QString("%1 ppm").arg(co2, 0, 'f', 0));
    }

    // 更新气压
    if (sensorData.contains("pressure")) {
        double pressure = sensorData["pressure"].toDouble();
        ui->label_pressure_value->setText(QString("%1 hPa").arg(pressure, 0, 'f', 1));
    }

    // 更新距离（如果有）
    if (sensorData.contains("distance")) {
        double distance = sensorData["distance"].toDouble();
        ui->label_distance_value->setText(QString("%1 cm").arg(distance, 0, 'f', 1));
    }

    qDebug() << "设备控制页面已更新传感器数据";
}

// 保留模拟数据更新函数作为备用
void Page_control::updateSensorDataSimulation()
{
    static bool increase = true;

    // 温度:25.0-30.0度之间变化
    static double temperature = 25.3;
    if (increase) {
        temperature += 0.1;
        if (temperature >= 30.0) increase = false;
    } else {
        temperature -= 0.1;
        if (temperature <= 25.0) increase = true;
    }
    ui->label_temp_value->setText(QString("%1°C").arg(temperature, 0, 'f', 1));

    // 湿度:50%-70%之间变化
    static int humidity = 57;
    humidity = 50 + qrand() % 21;
    ui->label_humidity_value->setText(QString("%1%").arg(humidity));

    // 光照:300-500 Lux之间变化
    static int light = 414;
    light = 300 + qrand() % 201;
    ui->label_light_value->setText(QString("%1 Lux").arg(light));

    // CO2浓度:400-600 ppm之间变化
    static int co2 = 474;
    co2 = 400 + qrand() % 201;
    ui->label_co2_value->setText(QString("%1 ppm").arg(co2));

    // 气压:1000-1020 hPa之间变化
    static int pressure = 1011;
    pressure = 1000 + qrand() % 21;
    ui->label_pressure_value->setText(QString("%1 hPa").arg(pressure));

    // 距离:5-20 cm之间变化
    static int distance = 12;
    distance = 5 + qrand() % 16;
    ui->label_distance_value->setText(QString("%1 cm").arg(distance));
}

void Page_control::sendControlCommand(const QString &deviceType, int deviceId,
                                     const QString &action, const QJsonObject &params)
{
    if (!m_dataMonitor) {
        qDebug() << "数据监控页面未连接,无法发送控制指令";
        return;
    }

    m_dataMonitor->sendDeviceControl(deviceType, deviceId, action, params);
}

void Page_control::updateLedStatus(int brightness)
{
    bool isOn = (brightness > 0);

    ui->btn_led_toggle->setText(isOn ? "开启" : "关闭");
    ui->btn_quick_led->setText(isOn ? "LED灯\n开启" : "LED灯\n关闭");

    if (isOn) {
        ui->btn_led_toggle->setStyleSheet("QPushButton:disabled { color: white; background-color: #4CAF50; }");
        ui->btn_quick_led->setStyleSheet("QPushButton:disabled { color: white; background-color: #4CAF50; }");
    } else {
        ui->btn_led_toggle->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");
        ui->btn_quick_led->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");
    }
}

void Page_control::updateFanStatus(int speed)
{
    bool isOn = (speed > 0);

    ui->btn_fan_toggle->setText(isOn ? "开启" : "关闭");
    ui->btn_quick_fan->setText(isOn ? "风扇\n运行中" : "风扇\n已停止");

    if (isOn) {
        ui->btn_fan_toggle->setStyleSheet("QPushButton:disabled { color: white; background-color: #2196F3; }");
        ui->btn_quick_fan->setStyleSheet("QPushButton:disabled { color: white; background-color: #2196F3; }");
    } else {
        ui->btn_fan_toggle->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");
        ui->btn_quick_fan->setStyleSheet("QPushButton:disabled { color: black; background-color: #e0e0e0; }");
    }
}

void Page_control::onLedBrightnessChanged(int value)
{
    ui->label_led_value->setText(QString("%1%").arg(value));
    updateLedStatus(value);
    m_pendingLedBrightness = value;
    m_ledBrightnessTimer->stop();
    m_ledBrightnessTimer->start(300);
}

void Page_control::onLedSliderReleased()
{
    m_ledBrightnessTimer->stop();
    sendLedBrightnessCommand();
}

void Page_control::sendLedBrightnessCommand()
{
    int value = m_pendingLedBrightness;
    QJsonObject params;
    params["brightness"] = value;
    QString action = (value > 0) ? "set_brightness" : "off";
    sendControlCommand("led", 1, action, params);
    qDebug() << "LED亮度设置为:" << value << "%, 状态:" << (value > 0 ? "开启" : "关闭");
}

void Page_control::onFanSpeedChanged(int value)
{
    ui->label_fan_value->setText(QString("%1%").arg(value));
    updateFanStatus(value);
    m_pendingFanSpeed = value;
    m_fanSpeedTimer->stop();
    m_fanSpeedTimer->start(300);
}

void Page_control::onFanSliderReleased()
{
    m_fanSpeedTimer->stop();
    sendFanSpeedCommand();
}

void Page_control::sendFanSpeedCommand()
{
    int value = m_pendingFanSpeed;
    QJsonObject params;
    params["speed"] = value;
    QString action = (value > 0) ? "set_speed" : "off";
    sendControlCommand("fan", 1, action, params);
    qDebug() << "风扇速度设置为:" << value << "%, 状态:" << (value > 0 ? "运行" : "停止");
}

void Page_control::onFanReverseToggle(bool checked)
{
    ui->btn_fan_reverse->setText(checked ? "开启" : "关闭");
    QString action = checked ? "reverse_on" : "reverse_off";
    sendControlCommand("fan", 1, action, QJsonObject());
    qDebug() << "风扇反转:" << (checked ? "开启" : "关闭");
}

void Page_control::onQuickCameraToggle(bool checked)
{
    ui->btn_quick_camera->setText(checked ? "摄像头\n开启" : "摄像头\n正常");
    QString action = checked ? "on" : "off";
    sendControlCommand("camera", 1, action, QJsonObject());
    qDebug() << "摄像头状态:" << (checked ? "开启" : "正常");
}

void Page_control::onQuickBuzzerToggle(bool checked)
{
    m_buzzerState = checked;
    updateBuzzerUI(checked);

    QString action = checked ? "on" : "off";
    sendControlCommand("buzzer", 1, action, QJsonObject());
    qDebug() << "蜂鸣器状态:" << (checked ? "报警" : "静音");
}
